package cn.com.scitc.servlet.paid;

import cn.com.scitc.dao.PaidDao;
import cn.com.scitc.model.Paid;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(urlPatterns = "/paid/create")
public class PaidCreateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            String paidType = req.getParameter("paidtype");
            String paidName = req.getParameter("paidname");

            String paidDateStr = req.getParameter("paiddate");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
            Date paidDate = sdf.parse(paidDateStr);

            BigDecimal amountPaid = new BigDecimal(req.getParameter("amountpaid"));
            String remark = req.getParameter("remark");

            Paid paid = new Paid();
            paid.setPaidtype(paidType);
            paid.setPaidname(paidName);
            paid.setPaiddate(paidDate);
            paid.setAmountpaid(amountPaid);
            paid.setRemark(remark);

            System.out.println("paidType: " + paidType);
            System.out.println("paidName: " + paidName);
            System.out.println("paidDate: " + paidDate);
            System.out.println("amountPaid: " + amountPaid);
            System.out.println("remark: " + remark);

            PaidDao paidDao = new PaidDao();
            paidDao.insert(paid);
            System.out.println("insert success");
            req.getSession().setAttribute("msg", "新增成功");

            //重定向, 跳转, list相对路径, "list", "./list"
            //resp.sendRedirect("list");

            //重定向, 跳转, list绝对路径，不推荐， /soft2102，硬代码
            //resp.sendRedirect("/soft2102/paid/list");

            String contextPath = req.getContextPath();
            String url = "/paid/list";
            if (!contextPath.equals("/")) {
                url = contextPath + url;
            }
            resp.sendRedirect(url);

        } catch (ParseException e) {
            System.out.println(e.getMessage());
        }
    }
}
